package com.news.service;

import com.news.dao.ArticleDao;
import com.news.exception.BusinessError;
import com.news.exception.BusinessException;
import com.news.model.ArticleEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lingzhiyuan.
 * Date : 15/10/9.
 * Time : 下午9:20.
 * Description:
 */

@Service
@Transactional
public class ArticleService {

    @Resource
    private ArticleDao articleDao;

    public Map findArticlesByColumnId(long column_id,int page_size,int page_num){

        Map result = articleDao.findArticleByColumnId(column_id, page_size, page_num);

        return result;
    }


    public void saveOrUpdate(long article_id, Long column_id, String source,String title, String content) {
        ArticleEntity article = null;
        long now = new Date().getTime();
        if (article_id == 0){
            article = new ArticleEntity();
            article.setDatetime(now);
        }else {
            article = articleDao.getById(ArticleEntity.class,article_id);
            if (article != null){
                article.setArticle_id(article_id);
            }else {
                throw new BusinessException(BusinessError.ERROR_ARTICLE_NOT_FOUND);
            }
        }

        article.setColumn_id(column_id);
        article.setSource(source);
        article.setTitle(title);
        article.setContent(content);
        articleDao.saveOrUpdate(article);
    }

    public List findAllArticlesByQueryKey(String queryKey) {

        return articleDao.findAllArticlesByQueryKey(queryKey.trim());
    }

    public void deleteColumn(Long article_id) {
        ArticleEntity articleEntity = articleDao.getById(ArticleEntity.class,article_id);
        if (articleEntity != null){
            articleDao.delete(articleEntity);
        }else {
            throw new BusinessException(BusinessError.ERROR_COLUMN_NOT_FOUND);
        }
    }

    public ArticleEntity getById(Long article_id) {

        return articleDao.getById(ArticleEntity.class,article_id);
    }
}
